require('dotenv').config()
var KS3 = require('ks3')
var STS = KS3.STS
var express = require('express')
var multipart = require('connect-multiparty');  
var multipartMiddleware = multipart(); 
var app = express();

const ak = process.env.AK || '<replace your ak>'
const sk = process.env.SK || '<replace your sk>'
let bucketName = process.env.bucketName || '<replace your bucketName>'
let endpoint = process.env.endpoint || '<replace your endpoint>' // 对应关系 https://docs.ksyun.com/documents/6761
const RoleKrn = process.env.RoleKrn || '<replace your RoleKrn>'


function consoleObject (obj) {
  Object.keys(obj).forEach(key => {
    if (key === 'headers') {
      console.log(`--------> ${key}: ${JSON.stringify(obj[key])}`)
    } else {
      console.log(`--------> ${key}: ${obj[key]}`)
    }
  })
}



app.all('*',function(req,res,next){
  //设置请求头
  //允许所有来源访问
  res.header('Access-Control-Allow-Origin', '*')
  //用于判断request来自ajax还是传统请求
  res.header('Access-Control-Allow-Headers', '*')
  //允许访问的方式
  res.header('Access-Control-Allow-Methods', '*')
  //内容类型：如果是post请求必须指定这个属性
  // res.header('Content-Type', 'application/json;charset=utf-8')
  if (req.method.toLowerCase() == 'options')
        res.send(200);  //让options尝试请求快速结束
    else next()
})



/**
 * 生成签名信息 put方式签名
 */
app.all('/getAuth', multipartMiddleware, (req, res) => {
  console.log('getAuth req.body: ', req.body)
  let {
    method,
    bucket,
    key,
    type,
    date = '',
    headers = {},
    body = ''
  } = req.body
  if (!key) {
    return res.json({
      msg: 'key must~'
    })
  }

  if (date) {
    headers = Object.assign({}, headers, {
      'x-kss-date': date
    })
  }
  // 存在x-amz-*时 Date置空
  if (headers) {
    const flag = Object.keys(headers).some(key => key.startsWith('x-amz-'))
    if (flag) date = ''
  }
  const param = {
    uri: '',
    method: method || 'PUT',
    body: '',
    type,
    date: date || '',
    resource: `/${bucket || bucketName }/${key}`,
    headers // x-kss相关的header
  }
  consoleObject(param)
  //对于后端服务 method  type date resource headers 需要参与计算，均为必传项 
  const signature = KS3.auth.generateToken(sk, param, body)

  res.status(200)
  const d = `KSS ${ak}:${signature}`
  console.log('authorization: ', d)
  res.json({
    type: 'success',
    result: {
      authorization: d,
      url: `http://${bucket || bucketName}.${endpoint}/${key}`
    }
  })

})


/**
 * 返回临时身份
 */
app.get('/getRole', (req, response) => {

  var client = new STS({
    ak,
    sk,
  });

  client.assumeRole({
    roleKrn: RoleKrn,
    roleSessionName: 'test' // 可按业务需求自定义
  }).then(result => {
    console.log(result)
    const res = JSON.parse(result)
    const credentials = res.AssumeRoleResult.Credentials
    const json = {
      AccessKeyId: credentials.AccessKeyId,
      AccessKeySecret: credentials.SecretAccessKey,
      SecurityToken: credentials.SecurityToken,
      Expiration: credentials.Expiration,
      BucketName: bucketName,
      Endpoint: endpoint
    }
    consoleObject(json)

    response.json(json);
  }).catch(err => {
    console.log(err);
    response.status(400).json(err.message);
  })
})


/**
 * 获取post上传的必要参数
 */
app.all('/post-policy', (req, res, next) => {
  var query = req.query;
  var now = Math.round(Date.now() / 1000);
  var exp = now + 900;
  var p = {
    'expiration': new Date(exp * 1000).toISOString(),
    'conditions': [
        // ['starts-with', '$Content-Type', 'image/'],
        // ['starts-with', '$success_action_redirect', redirectUrl],
        // ['eq', '$x-cos-server-side-encryption', 'AES256'],
        ["eq", "$bucket", query.bucket|| bucketName],
        ['eq', '$key', query.key],
        ['eq', '$acl', query.acl]
    ]
  }

  if(query.redirect) {
    p.conditions.push(['eq', '$redirect', query.redirect])
  }

  var policy = JSON.stringify(p);

  const signature = KS3.auth.getFormSignature(sk, policy)


  //---------------------------输出参数便于调试-----------------------------
  console.log('--------------------------------------')
  const obj = {
    AK: ak,
    SecreteKey: sk,
    currentTimestamp: now,
    expireTimestamp: exp,
    conditions: policy,
    policy: Buffer.from(policy).toString('base64'),
    Signature: signature,
    redirect: query.redirect
  }
  consoleObject(obj)
  //---------------------------------------------------------------------
  
  res.json({
    type: 'success',
    result: {
      url: `http://${endpoint}/${query.bucket|| bucketName}`,
      policyObj: JSON.parse(policy),
      policy: Buffer.from(policy).toString('base64'),
      Ak: ak,
      Signature: signature,
      redirect: query.redirect
      // securityToken: securityToken, // 如果使用临时密钥，要返回在这个资源 sessionToken 的值
    }
  });
})


app.listen('3000', function () {
    console.log('backend server has started, http://localhost:3000')
})